package com.wzapp.sitposture.authentication.endpoint;

import com.alibaba.fastjson.JSONObject;
import com.wzapp.sitposture.authentication.pojo.param.FetchMobileParam;
import com.wzapp.sitposture.authentication.pojo.param.ValidMobileParam;
import com.wzapp.sitposture.authentication.pojo.view.OssDTO;
import com.wzapp.sitposture.authentication.pojo.view.OssRequest;
import com.wzapp.sitposture.authentication.pojo.view.SmsCode;
import com.wzapp.sitposture.authentication.service.AuthenticationService;
import com.wzapp.sitposture.common.base.BaseEndpoint;
import com.wzapp.sitposture.common.base.HeaderParam;
import com.wzapp.sitposture.common.error.CustomizedException;
import com.wzapp.sitposture.common.restful.RestfulResult;
import com.wzapp.sitposture.common.util.ToolUtil;
import com.wzapp.sitposture.config.redis.service.RedisService;
import com.wzapp.sitposture.easemob.comm.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by qianglong on 2018/1/15.
 */
@Slf4j
@RequestMapping("/authentication")
@RestController
public class AuthenticationEndpoint extends BaseEndpoint {

    @Autowired
    AuthenticationService authenticationService;

    @Autowired
    RedisService redisService;

    /**
     * 功能: 获取七牛Token<br/>
     *
     * @param
     * @return java.util.List<Oss>
     * @author ql
     * @create 2018/5/7 19:45
     **/
    @GetMapping("/osses")
    public List<OssDTO> getOsses(OssRequest ossRequest) throws CustomizedException {

        return authenticationService.requestOss(ossRequest);
    }


    /**
     * 功能: 获取短信验证码<br/>
     *
     * @param fetchMobileRequest
     * @return com.ql.authentication.backup.SmsCode
     * @author ql
     * @create 2018/5/7 19:46
     **/
    @GetMapping("/codes/action/fetchByMobile")
    public SmsCode fetchByMobile(@Valid FetchMobileParam fetchMobileRequest) throws Exception {
        String mobile = fetchMobileRequest.getMobile();
        if (ToolUtil.isEmpty(mobile)) {
            throw new CustomizedException("public.param.blank","手机号码");
        }

        HeaderParam headerParam = super.getHeaderParam();
        String ip = headerParam.getRemoteIp();
        String key ="ip_" + ip;
        String permanentKey ="ip_permanent_" + ip;
        if(redisService.exists(permanentKey)){
            log.error("===fetchByMobile 同一ip={},mobile={}多次重复请求，永久封杀====",ip,mobile);
            throw new CustomizedException("authentication.code.request.busy");
        }
        Object countObj = redisService.get(key);
        //超过5次，直接封掉
        if(countObj != null && Long.parseLong(countObj.toString()) > 5){
            redisService.increment(key,1L,24*60*60L);
            log.error("===fetchByMobile 同一ip={},mobile={}多次重复请求，封杀24小时====",ip,mobile);
            throw new CustomizedException("authentication.code.repeat.error","60");
//            throw new CustomizedException("authentication.code.request.busy");
        }else {
            //1小时失效
            redisService.increment(key,1L,3600L);
        }

        mobile = mobile.trim();
        //只支持大陆11位手机号码
        if (mobile.length() != 11) {
            throw new CustomizedException("authentication.mobile.format.error");
        }
        return authenticationService.fetchByMobile(mobile, fetchMobileRequest.getType());
    }

    /**
     * 功能: 获取短信验证码<br/>
     *
     * @param validMobileParam
     * @return com.ql.authentication.backup.SmsCode
     * @author ql
     * @create 2018/9/29 14:46
     **/
    @GetMapping("/codes/action/valid_mobile_code")
    public ResponseEntity validMobileCode(@Valid ValidMobileParam validMobileParam) throws Exception {

        Boolean isLegal = authenticationService.validMobileCode(validMobileParam);

        JSONObject reslut = new JSONObject();
        if (isLegal) {
            reslut.put("message", "success");
            reslut.put("code", 200);
        } else {
            reslut.put("code", 204);
            reslut.put("message", "failed");
        }
        return RestfulResult.ok(reslut);
    }

    /**
     * 功能: 获取环信token<br/>
     *
     * @author qianglong
     * @create 2019/1/6 17:44
     * @param 
     * @return org.springframework.http.ResponseEntity
     **/
    @GetMapping("/im_token")
    public ResponseEntity getIMToken(){
        JSONObject object = new JSONObject();
        object.put("im_token",TokenUtil.getAccessToken());
        return RestfulResult.ok(object);
    }
}
